<?php


namespace app\common\model;

use app\common\model\ProfitLog;

class GrowthLog extends Base
{
    // 设置当前模型对应的完整数据表名称
    protected $table = 'ddt_growth_log';
    // 主键ID
    protected $pk = 'log_id';

	//订单状态
	public static $typelist = [
		'1'=>'线上购买商品',
		'2'=>'线下点餐',
		'3'=>'签到',
		'4'=>'分润',
		'5'=>'后台添加',
		'6'=>'兑换商品',
	];

	public function getTypeCase($type){
		switch ($type){
			case 1:
				$cate = '+';
				break;
			case 2:
				$cate = '+';
				break;
			case 3:
				$cate = '+';
				break;
			case 4:
				$cate = '+';
				break;
			case 5:
				$cate = '+';
				break;
			case 6:
				$cate = '-';
				break;
		}
		return $cate;
	}

	/**
	 * 记录积分变动
	 * @param $user_id
	 * @param $type
	 * @param $note
	 * @param $value
	 * @param $growth_coin
	 * @return bool
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 */
    function ChangeValueLog($user_id,$type,$value,$note,$growth_coin)
    {
		$typelist = GrowthLog::$typelist;
		if (@!$typelist[$type]){
			return false;
		}

		$this->startTrans();

		$cate = $this->getTypeCase($type);

		$data = [
			'user_id' => $user_id,
			'cate' => $cate,
			'type' => $type,
			'change_value' => $value,
			'value_show' => $cate.$value,
			'value' => $growth_coin,
			'note' => $note,
			'add_time' => time(),
		];
//		print_r($data);die;

		$res = $this->save($data);
		if(!$res){
			return false;
		}
		$this->commit();
		return $this->{$this->pk};
	}

	// 获取用户积分记录
    function get_growth_record($condition,$field,$orderby = null,$limit){
        $where = null;
        if(!empty($condition['user_id'])){
            $where[] = ['user_id','=',$condition['user_id']];
        }
        $rs = $this
            ->where($where)
            ->field($field)
            ->where($where)
            ->order($orderby)
            ->paginate($limit);
        return $rs;
    }

//    插入兑换商品的积分记录
    function exchangerecord($orderid,$userinfo){
        $OrderModel = new Order();
        $join = [['ddt_shops s','o.shop_id = s.shop_id'],['ddt_orderdetail od','o.order_id = od.order_id']];
        $msginfo = $OrderModel->getJoinOrder([['o.order_id','=',$orderid]],'o.points,od.product_name,od.p_s_name,s.shop_name',$join);
        $note = $msginfo['shop_name'].'兑换'.$msginfo['product_name'].'('.$msginfo['p_s_name'].')';
        $rs = $this->ChangeValueLog($userinfo['user_id'],6,$msginfo['points'],$note,$userinfo['growth_coin']);
        if($rs === false){
            return false;
        }
        return true;
    }

	/**
	 * 计算让利折扣出来的利润分配
	 * @param $userInfo
	 * @param $paymentsInfo
	 * @param $type
	 * @return bool
	 * @throws \think\Exception
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 * @throws \think\exception\PDOException
	 */
	function CalculateProfit($userInfo,$paymentsInfo,$type){
		//计算让利分润额度
		//平台（40%） 用户（30%） 推销员（30%）
		$amount = $paymentsInfo['amount'];//订单金额
		$percentage = calculate([$paymentsInfo['profit'],100],'/','2');//店铺让利百分比
		$profit = calculate([$amount,$percentage],'*',2);//计算出来的总利润
		$platform_profit = calculate([$profit,0.4],'*',2);//平台获取的利润
		$user_profit = calculate([$profit,0.3],'*',2);//用户获取的利润
		$sales_profit = calculate([$profit,0.3],'*',2);//推销员获取的利润

		$profitdata = [
			'shop_id' => $paymentsInfo['shop_id'],
			'order_id' => $paymentsInfo['order_id'],
			'user_id' => $userInfo['user_id'],
			'sales_user_id' => $paymentsInfo['sale_id'],
			'type' => $type,
			'amount' => $amount,
			'percentage' => $percentage,
			'profit' => $profit,
			'platform_profit' => $platform_profit,
			'user_profit' => $user_profit,
			'sales_profit' => $sales_profit,
			'add_time' => time(),
		];
		$ProfitLogModel = new ProfitLog();
		$ProfitLogID = $ProfitLogModel->save($profitdata);
		if(!$ProfitLogID){
			$this->setError(-1,'记录失败101');
			return false;
		}

		$note = '用户单号'.trim($paymentsInfo['orderno'],',').'下单购买商品获得总购物积分';
		$i_rs = $this->ChangeValueLog($userInfo['user_id'],$type,$user_profit,$note,$userInfo['growth_coin']);
		if($i_rs === false){
			$this->setError(-1,'插入积分记录失败');
			$this->rollback();
			return false;
		}

		$userModel = new User();
		$u_rs = $userModel->where("user_id",'=',$userInfo['user_id'])->setInc('growth_coin',$user_profit);
		if($u_rs === false){
			$this->setError(-1,'更新用户购买积分失败');
			return false;
		}

		return [
			'amount' => $amount,//订单金额
			'percentage' => $percentage,//店铺让利百分比
			'profit' => $profit,//计算出来的总利润
			'platform_profit' => $platform_profit,//平台获取的利润
			'user_profit' => $user_profit,//用户获取的利润
			'sales_profit' => $sales_profit,//推销员获取的利润
		];
	}
}